package com.moyobar.app.consumer;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;

public class Demo {

	public static void main(String[] args) throws Exception{
		
		ApplicationConfig application = new ApplicationConfig();
		application.setName("yyy");
		 
		// 连接注册中心配置
		RegistryConfig registry = new RegistryConfig();
		registry.setAddress("zookeeper://127.0.0.1:2181");
	
		
		String file = "/Users/Rocky/Git/exampels/samples/api-gateway/api/target/api-0.0.1-SNAPSHOT.jar";
		
		JarFile jar = new JarFile(new File(file));
		Enumeration<JarEntry> entries = jar.entries();
		
		ClassLoader loader = new URLClassLoader(new URL[]{new URL("file:"+file)});
		
		
		
		while(entries.hasMoreElements()){
			JarEntry entry = entries.nextElement();
			if(!entry.isDirectory() && entry.getName().endsWith("UserService.class")){
				String className = entry.getName().replaceAll("\\/", ".").replace(".class", "");
				Class<?> clazz = loader.loadClass(className);
			
				
				
				ReferenceConfig reference = new ReferenceConfig();
				reference.setApplication(application);
				reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
				reference.setInterface(clazz);
				
				Object invoker = reference.get();
				
				Method method = clazz.getMethod("get", String.class);
				Object obj = method.invoke(invoker, "1");
				
				Class<?> returnType = method.getReturnType();
				Method[] methods = returnType.getDeclaredMethods();
				for(Method m:methods){
					if(m.getName().startsWith("get")){
						Object o = m.invoke(obj, null);
						System.out.println(o);
					}
				}
				
			}
		}
		
		
		
	}
}
